package org.example.classtopia.Service.Impl;

import org.example.classtopia.Mapper.ResourceMapper;
import org.example.classtopia.Mapper.UserMapper;
import org.example.classtopia.Model.Entity.Resource;
import org.example.classtopia.Model.Entity.User;
import org.example.classtopia.Model.dto.ResourceUploadDTO;
import org.example.classtopia.Service.ResourceService;
import org.example.classtopia.Utils.AliOSSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import org.example.classtopia.Model.dto.ResourcePageQueryDTO;
import org.example.classtopia.Model.dto.UserResourcePageQueryDTO;
import org.example.classtopia.Model.vo.ResourceDetailVO;
import org.example.classtopia.Model.vo.ResourceListVO;
import org.example.classtopia.Model.vo.PageResultVO;
import org.example.classtopia.Model.vo.ResourceStatsVO;

@Service
public class ResourceServiceImpl implements ResourceService {
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private AliOSSUtils ossUtil;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Long uploadResource(ResourceUploadDTO dto, MultipartFile file) throws Exception {
        // 根据userId获取用户信息
        User user = userMapper.FindCommonData(dto.getUserId());
        if (user == null) {
            throw new Exception("用户不存在");
        }
        
        // 上传文件到OSS，获取URL
        String fileUrl = ossUtil.upload(file, "classtopia-file");
        // 组装Resource对象
        Resource resource = new Resource();
        resource.setUserId(dto.getUserId());
        resource.setUserNickname(user.getNickname());
        resource.setUserAvatar(user.getAvatar());
        resource.setTitle(dto.getTitle());
        resource.setDescription(dto.getDescription());
        resource.setFileUrl(fileUrl);
        resource.setFileSize(file.getSize());
        // 只存扩展名
        String originalFilename = file.getOriginalFilename();
        String fileType = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        resource.setFileType(fileType); // 例如 .pdf
        resource.setCategoryId(dto.getCategoryId());
        resource.setDownloadCount(0);
        resource.setLikeCount(0);
        resource.setStatus(1);
        resource.setCreatedAt(new Date());
        resource.setUpdatedAt(new Date());
        // 插入数据库
        resourceMapper.insertResource(resource);
        return resource.getId();
    }

    @Override
    public Resource downloadResource(Long resourceId, Long userId) throws Exception {
        System.out.println("下载资源ID: " + resourceId + ", 用户ID: " + userId);
        Resource resource = resourceMapper.selectResourceById(resourceId);
        System.out.println("查到的资源: " + resource);
        if (resource == null || resource.getStatus() == 0) {
            throw new Exception("资源不存在或已被删除");
        }
        int updated = resourceMapper.incrementDownloadCount(resourceId);
        System.out.println("下载次数更新行数: " + updated);
        return resource;
    }

    @Override
    public PageResultVO<ResourceListVO> pageList(ResourcePageQueryDTO queryDTO) {
        // 参数校验与默认值
        if (queryDTO.getPageNum() == null || queryDTO.getPageNum() < 1)
            queryDTO.setPageNum(1);
        if (queryDTO.getPageSize() == null || queryDTO.getPageSize() < 1)
            queryDTO.setPageSize(10);
        // 兼容前端传0或-1时，视为全部分类
        if (queryDTO.getCategoryId() != null && (queryDTO.getCategoryId() == 0 || queryDTO.getCategoryId() == -1)) {
            queryDTO.setCategoryId(null);
        }
        // 新增：fileType为null或空字符串时不作为条件
        if (queryDTO.getFileType() != null && queryDTO.getFileType().trim().isEmpty()) {
            queryDTO.setFileType(null);
        }
        System.out.println("Resource search keyword: " + queryDTO.getKeyword());
        // 查询数据
        List<ResourceListVO> records = resourceMapper.selectResourcePage(queryDTO);
        Long total = resourceMapper.countResourcePage(queryDTO);
        int totalPages = (int) ((total + queryDTO.getPageSize() - 1) / queryDTO.getPageSize());
        // 封装分页VO
        PageResultVO<ResourceListVO> pageResult = new PageResultVO<>();
        pageResult.setRecords(records);
        pageResult.setPageNum(queryDTO.getPageNum());
        pageResult.setPageSize(queryDTO.getPageSize());
        pageResult.setTotal(total);
        pageResult.setTotalPages(totalPages);
        return pageResult;
    }

    @Override
    public PageResultVO<ResourceListVO> pageListByUser(UserResourcePageQueryDTO queryDTO) {
        if (queryDTO.getPageNum() == null || queryDTO.getPageNum() < 1)
            queryDTO.setPageNum(1);
        if (queryDTO.getPageSize() == null || queryDTO.getPageSize() < 1)
            queryDTO.setPageSize(10);
        List<ResourceListVO> records = resourceMapper.selectResourcePageByUser(queryDTO);
        Long total = resourceMapper.countResourcePageByUser(queryDTO);
        int totalPages = (int) ((total + queryDTO.getPageSize() - 1) / queryDTO.getPageSize());
        PageResultVO<ResourceListVO> pageResult = new PageResultVO<>();
        pageResult.setRecords(records);
        pageResult.setPageNum(queryDTO.getPageNum());
        pageResult.setPageSize(queryDTO.getPageSize());
        pageResult.setTotal(total);
        pageResult.setTotalPages(totalPages);
        return pageResult;
    }

    @Override
    public boolean updateResourceStatus(Long resourceId, Integer status) {
        return resourceMapper.updateResourceStatus(resourceId, status) > 0;
    }

    @Override
    public String uploadImage(org.springframework.web.multipart.MultipartFile file) throws Exception {
        // 直接调用OSS工具类，目录为classtopia-file
        return ossUtil.upload(file, "classtopia-file");
    }

    @Override
    public ResourceStatsVO getResourceStats() {
        ResourceStatsVO vo = new ResourceStatsVO();
        vo.setTotalCount(resourceMapper.countAllResources());
        vo.setContributorCount(resourceMapper.countDistinctContributors());
        vo.setTotalDownload(resourceMapper.sumDownloadCount());
        return vo;
    }
}
